#include<bits/stdc++.h>
#define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define debug  freopen("in.txt","r",stdin),freopen("out.txt","w",stdout);
#define fs first
#define sc second
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 1e5+10;
using namespace std;

int N,M;
bool vis[maxn];
int dis[maxn];
int h[maxn],e[maxn*2],ne[maxn*2],idx;
void add(int a,int b){
	e[++idx] = b,ne[idx] = h[a],h[a] = idx;
}
priority_queue<pii,vector<pii>,greater<pii>> q;

void dij(int s){
	memset(dis,0x3f,sizeof dis);
	dis[s] = 0;
	q.push({0,s});

	while(q.size()){
		auto cur = q.top();q.pop();
		int d = cur.fs,u = cur.sc;
		if(vis[u]) continue;
		vis[u] = true;
		for(int i = h[u];i;i = ne[i]){
			int v = e[i];
			if(d + 1 < dis[v]){
				dis[v] = d + 1;
				q.push({dis[v],v});
			}
		}
	}
}

int main(){
	// debug;
	ios;

	cin>>N>>M;
	for(int i = 1;i<=M;i++){
		int x,y;cin>>x>>y;
		add(x,y);
		add(y,x);
	}
	dij(1);
	cout<<dis[N]-1<<'\n';

	return 0;
}
